import { CloseOutlined } from '@ant-design/icons'
import { App, Button, List } from 'antd'
import { Empty } from '@/desktop/components'
import ChooseExternalTagsModal from '@/desktop/components/ChooseExternalTags'
import { colors, breakWord } from '@/desktop/styles'
import { unique } from '@/lib/utils'
import services from '@/services'
import type { ExternalTag } from '@/services/contact-types'
import { type Editing } from './index'

export function useTags(corpIds: string[]) {
  const { message } = App.useApp()
  const [allTags, setAllTags] = useState<ExternalTag[]>([])
  useEffect(() => {
    void services.externals.tags.getAllTags(corpIds).then(res => {
      if (res.success) setAllTags(res.data)
      else {
        void message.error(`标签加载失败：${res.error}`)
        setAllTags([])
      }
    })
  }, [message, corpIds])
  return allTags
}

export function ChooseTargetByTag({
  editing,
  tagIds,
  setTagIds,
}: {
  editing: Editing
  tagIds: string[]
  setTagIds: (ids: string[]) => void
}) {
  const corpIds = useMemo(() => {
    return unique(editing.qywxs.map(v => v.corpid))
  }, [editing])

  const allTags = useTags(corpIds)
  const choosedTags = useMemo(
    () => allTags.filter(tag => tagIds.includes(tag.id)),
    [tagIds, allTags],
  )

  const [choosing, setChoosing] = useState(false)
  function cancelChoose(tagId: string) {
    setTagIds(tagIds.filter(v => v !== tagId))
  }

  return <>
    {!tagIds.length ? (
      <div css={s.emptyTags}>
        <Empty description="尚未选择标签" />
        <Button type="primary" onClick={() => setChoosing(true)}>
          选择标签
        </Button>
      </div>
    ) : null}

    {tagIds.length ? (
      <div css={s.tagsWrap}>
        <div css={s.tagsInner}>
          <Button type="primary" onClick={() => setChoosing(true)}>
            选择标签
          </Button>
          <List
            bordered
            dataSource={choosedTags}
            renderItem={tag => <List.Item
              actions={[
                <CloseOutlined css={s.remove} key="remove" onClick={() => cancelChoose(tag.id)} />,
              ]}
            >
              <div css={s.name}>{tag.name}</div>
            </List.Item>}
            rowKey="id"
          />
        </div>
      </div>
    ) : null}

    <ChooseExternalTagsModal
      visible={choosing}
      title="选择客户标签"
      corpIds={corpIds}
      choosed={tagIds}
      onFinish={tags => {
        if (tags) setTagIds(tags.map(v => v.id))
        setChoosing(false)
      }}
    />
  </>
}

const s = {
  emptyTags: css`
    padding: 30px 0;
    text-align: center;
  `,
  tagsWrap: css`
    flex-shrink: 1;
    overflow: hidden;
    padding: 20px 0;
  `,
  tagsInner: css`
    display: flex;
    flex-direction: column;
    margin: 0 auto;
    max-height: 100%;
    max-width: 700px;
    overflow: hidden;
    button {
      align-self: flex-start;
      margin-bottom: 12px;
    }
    .ant-list {
      flex-shrink: 1;
      overflow-y: auto;
    }
  `,
  name: css`
    ${breakWord};
  `,
  remove: css`
    color: ${colors.error};
  `,
}
